<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-button type="primary"
                 @click="showAddCateDialog">添加分类</el-button>
      <!-- 表格 -->
      <tree-table class="treeTable"
                  :data="cateList"
                  :columns="columns"
                  :selection-type="false"
                  :expand-type="false"
                  show-index
                  index-text="#"
                  border>
        <!-- 是否有效 -->
        <template v-slot:isok="scope">
          <i class="el-icon-success"
             v-if="scope.row.cat_deleted === false"
             style="color: green"></i>
          <i class="el-icon-error"
             v-else
             style="color: red"></i>
        </template>

        <!-- 排序 -->
        <template v-slot:order="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success"
                  v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning"
                  v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template v-slot:opt="scope">
          <el-button type="primary"
                     icon="el-icon-edit"
                     size="mini"
                     @click="showEditCateDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger"
                     icon="el-icon-delete"
                     size="mini"
                     @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[3, 5, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类"
               :visible.sync="addCateDialogVisible"
               width="50%"
               @close="addCateDialogClosed">
      <el-form ref="addCateFormRef"
               :model="addCateForm"
               label-width="100px"
               :rules="addCateFormRules">
        <el-form-item label="分类名称: "
                      prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类: ">
          <!-- option用来指定数据源 -->
          <!-- props用来指定配置对象 -->
          <el-cascader :options="parentCateList"
                       :props="cascaderProps"
                       v-model="selectedKeys"
                       @change="parentCateChanged"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title="修改分类"
               :visible.sync="editDialogVisible"
               width="50%">
      <el-form ref="editCateFormRef"
               :model="editCateForm"
               label-width="100px"
               :rules="editCateFormRules">
        <el-form-item label="分类名称: "
                      prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCateData, getParentCateList, addCate, getCateById, editCate, deleteCateById } from '../../network/goods';
export default {
  name: 'GoodsCategories',
  data () {
    return {
      //商品分类的数据列表
      cateList: [],
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //数据总条数
      total: 0,
      //为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          //表示当前列定义为模板列
          type: 'template',
          //表示当前这一列使用的模板名称
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      //控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //将要添加的分类的名称
        cat_name: '',
        // 分类父 ID
        cat_pid: 0,
        // 分类层级 默认一级
        cat_level: 0
      },
      //添加分类表单的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ]
      },
      //父级分类的列表
      parentCateList: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //选中的父级分类的Id数组
      selectedKeys: [],
      //控制编辑对话框的显示与隐藏
      editDialogVisible: false,
      //编辑分类的数据对象
      editCateForm: {
        cat_name: '',
        cat_id: ''
      },
      //编辑分类的验证规则对象
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ]
      },
    }
  },
  created () {
    this.getCateList();
  },
  methods: {
    //获取商品分类的数据
    async getCateList () {
      const res = await getCateData(this.queryInfo);
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败');
      }
      //把数据列表赋值给cateList
      this.cateList = res.data.result;
      //把数据总条数赋值给total
      this.total = res.data.total;
    },

    //监听pagesize改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },

    //监听pagenum改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },

    //点击按钮，展示添加分类的对话框
    showAddCateDialog () {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },

    //获取父级分类的数据列表
    async getParentCateList () {
      const res = await getParentCateList();
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败');
      }
      this.parentCateList = res.data;
    },

    //选择项发生变化触发这个函数
    parentCateChanged () {
      //console.log(this.selectedKeys);
      if (this.selectedKeys.length > 0) {
        //父级分类的id
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },

    //点击按钮，添加新的分类
    addCate () {
      //console.log(this.addCateForm);
      this.$refs.addCateFormRef.validate(async valid => {
        //console.log(valid);
        if (!valid) return;
        const res = await addCate(this.addCateForm);
        //console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败');
        }
        this.$message.success('添加分类成功');
        this.getCateList();
        this.addCateDialogVisible = false;
      })
    },

    //监听分类对话框的关闭事件，重置表单数据
    addCateDialogClosed () {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },

    //展示编辑对话框
    async showEditCateDialog (cateId) {
      this.editCateForm.cat_id = cateId;
      const res = await getCateById(cateId);
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类名称失败');
      }
      this.editCateForm.cat_name = res.data.cat_name;
      this.editDialogVisible = true;
    },

    //编辑分类名称
    editCate () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return;
        const res = await editCate(this.editCateForm.cat_id, this.editCateForm.cat_name);
        if (res.meta.status !== 200) {
          return this.$message.error('分类名称更新失败');
        }
        this.$message.success('分类名称更新成功');
        this.getCateList();
        this.editDialogVisible = false;
      })
    },

    //删除分类
    async deleteCate (cat_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }

      const res = await deleteCateById(cat_id);
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败');
      }
      this.$message.success('删除分类成功');
      this.getCateList();
    }
  },
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}

.el-cascader {
  width: 100%;
}
</style>